<template>
  <div :id="lineId" class="lineChart-box" :yData="yData" :xData="xData" :lineTitle="lineTitle">
    <div :id="'main'+random" :style="{'height':height+'px'}"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import { computed, onMounted, reactive, ref, toRefs, watch } from 'vue';
export default {
  props: {
    yData: {
      type: Array,
      default: [],
    },
    xData: {
      type: Array,
      default: [],
    },
    lineTitle: {
      type: String,
      default: '',
    },
    lineId: {
      type: String,
      default: '',
    },
    height: {
      type: Number,
      default: 0,
    },
    minInterval: {
      type: Number,
      default: 0.1,
    },
  },


  setup(props, context) {
    let myChart = null

    const state = reactive({
      random: (Math.random() + 1) * 100,
    })

    watch(() => props.yData, (newVal, oldVal) => {
      init()
    })

    function init() {
      myChart && myChart.clear()
      const lineBox = document.getElementById('main' + state.random)
      myChart = echarts.init(lineBox)
      const option = {
        title: {
          text: props.lineTitle || '',
        },
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          data: props.xData || [],
        },
        yAxis: {
          type: 'value',
          minInterval: props.minInterval,
          min: function (value) {
            return Math.floor(value.min)
          },
          max: function (value) {
            return Math.ceil(value.max)
          },
        },
        series: [
          {
            data: props.yData || [],
            type: 'line'
          }
        ]
      }
      myChart.setOption(option, true)
    }

    onMounted(() => {
      window.addEventListener("resize", function () {
        myChart && myChart.resize();
      })
    })

    return {
      ...toRefs(state),
      init,
    }
  }
}
</script>

<style>
</style>